<template>
  <view class="register-container">
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        <text>返回</text>
      </view>
      <view class="header-title">注册账号</view>
      <view class="header-right"></view>
    </view>

    <view class="content">
      <view class="step-indicator">
        <view class="step" :class="{active: currentStep >= 1}">
          <view class="step-number">1</view>
          <text class="step-text">填写信息</text>
        </view>
        <view class="step-line" :class="{active: currentStep >= 2}"></view>
        <view class="step" :class="{active: currentStep >= 2}">
          <view class="step-number">2</view>
          <text class="step-text">注册成功</text>
        </view>
      </view>

      <!-- 步骤1：填写信息 -->
      <view v-if="currentStep === 1" class="step-content">
        <view class="form-section">
          <view class="form-item">
            <view class="form-label">姓名</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.name" placeholder="请输入姓名" maxlength="20" />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">身份证号</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.idNumber" placeholder="请输入身份证号" maxlength="18" />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">交易密码</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.password" placeholder="请输入6以上位交易密码" type="password" maxlength="6" inputmode="numeric" pattern="[0-9]*" />
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">确认密码</view>
            <view class="form-input-group">
              <input class="form-input" v-model="formData.confirmPassword" placeholder="请再次输入交易密码" type="password" maxlength="6" inputmode="numeric" pattern="[0-9]*" />
            </view>
          </view>

          <view class="password-tips">
            <u-icon name="info-circle" size="16" color="#999"></u-icon>
            <text class="tip-text">交易密码为6位数字</text>
          </view>
        </view>

        <view class="agreement-section">
          <checkbox-group @change="handleAgreementChange">
            <checkbox :checked="formData.agreement" value="agree" color="#1989fa" />
          </checkbox-group>
          <text class="agreement-text" @click="toggleAgreement">我已阅读并同意<text class="link-text" @click="viewAgreement('register_agreement')">《用户协议》</text>和<text class="link-text" @click="viewAgreement('privacy_agreement')">《隐私政策》</text></text>
        </view>

        <button class="action-btn" @click="register">注册</button>
      </view>

      <!-- 步骤2：注册成功 -->
      <view v-if="currentStep === 2" class="step-content">
        <view class="success-section">
          <view class="success-icon">
            <u-icon name="checkmark-circle" size="80" color="#07c160"></u-icon>
          </view>
          <view class="success-title">注册成功</view>
          <view class="success-desc">您已成功注册账号，现在可以登录使用</view>
        </view>

        <button class="action-btn" @click="goToLogin">立即登录</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentStep: 1,
      formData: {
        name: '',
        idNumber: '',
        password: '',
        confirmPassword: '',
        agreement: false
      }
    }
  },
  methods: {
    viewAgreement(type) {
      uni.navigateTo({
        url: '/pages/contract/agreement?type=' + type
      })
    },
    goBack() {
      if (this.currentStep === 2) {
        uni.reLaunch({
          url: '/pages/login/index'
        });
      } else {
        uni.navigateBack();
      }
    },
    handleAgreementChange(e) {
      // checkbox-group 的 change 事件返回的是选中的 value 数组
      this.formData.agreement = e.detail.value.length > 0;
    },

    toggleAgreement() {
      this.formData.agreement = !this.formData.agreement;
    },
    checkIdNumber(idNumber) {
        // 正则表达式验证身份证格式
        const reg = /^(?:\d{15}|\d{17}[\dX])$/;
        if (!reg.test(idNumber)) {
            console.error('身份证号码格式不正确');
            return false;
        }

        // 如果是18位身份证，进行校验位验证
        if (idNumber.length === 18) {
            const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            const checkDigits = '10X98765432';
            let sum = 0;

            for (let i = 0; i < 17; i++) {
                sum += idNumber[i] * weights[i];
            }

            const checkDigit = checkDigits[sum % 11];
            if (checkDigit !== idNumber[17]) {
                console.error('身份证号码校验位不正确');
                return false;
            }
        }

        console.log('身份证号码有效');
        return true;
    },
    register() {
      console.log('注册表单数据:', this.formData);

      if (!this.formData.name) {
        return uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        });
      }

      if (!this.formData.idNumber || !this.checkIdNumber(this.formData.idNumber)) {
        return uni.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        });
      }

      if (!this.formData.password) {
        return uni.showToast({
          title: '请设置交易密码',
          icon: 'none'
        });
      }

      if (this.formData.password.length !== 6) {
        return uni.showToast({
          title: '交易密码必须为6位数字',
          icon: 'none'
        });
      }

      if (!this.formData.confirmPassword) {
        return uni.showToast({
          title: '请确认交易密码',
          icon: 'none'
        });
      }

      if (this.formData.password !== this.formData.confirmPassword) {
        return uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        });
      }

      console.log('协议勾选状态:', this.formData.agreement);
      if (!this.formData.agreement) {
        return uni.showToast({
          title: '请阅读并同意用户协议和隐私政策',
          icon: 'none'
        });
      }

      // 调用注册接口
      uni.showLoading({
        title: '注册中...'
      });

      this.$store.dispatch('Register', this.formData).then((res) => {
        console.log('注册成功，开始处理后续流程', res);
        uni.hideLoading();

        // 注册成功
        uni.showToast({
          title: '注册成功',
          icon: 'success'
        });

        // 获取用户信息
        console.log('开始获取用户信息');
        this.$store.dispatch('GetUserInfo').then((userRes) => {
          console.log('获取用户信息成功:', userRes);
          // 进入注册成功页面
          this.currentStep = 2;
        }).catch(userErr => {
          console.error('获取用户信息失败:', userErr);
          // 即使获取用户信息失败，也进入注册成功页面
          this.currentStep = 2;
        });
      }).catch(error => {
        console.error('注册失败，完整错误信息:', error);
        uni.hideLoading();

        // 尝试提取更详细的错误信息
        let errorMsg = '注册失败，请稍后再试';
        if (error) {
          if (typeof error === 'string') {
            errorMsg = error;
          } else if (error.message) {
            errorMsg = error.message;
          } else if (error.errMsg) {
            errorMsg = error.errMsg;
          }
        }

        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 3000
        });
      });
    },

    goToLogin() {
      // 注册成功后，用户已经登录，直接跳转到首页
      uni.switchTab({
        url: '/pages/home/index'
      });
    }
  }
}
</script>

<style lang="scss">
.register-container {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

.content {
  padding: 30rpx;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 50rpx;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-number {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #ddd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  margin-bottom: 10rpx;
}

.step.active .step-number {
  background-color: #1989fa;
}

.step-text {
  font-size: 24rpx;
  color: #999;
}

.step.active .step-text {
  color: #1989fa;
}

.step-line {
  width: 100rpx;
  height: 2rpx;
  background-color: #ddd;
  margin: 0 15rpx;
  margin-bottom: 30rpx;
}

.step-line.active {
  background-color: #1989fa;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.form-input-group {
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  height: 80rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.eye-icon {
  padding: 0 20rpx;
}

.password-tips {
  display: flex;
  align-items: flex-start;
  margin-top: 20rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
  flex: 1;
}

.agreement-section {
  display: flex;
  align-items: center;
  margin: 30rpx 0;
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
  margin-left: 10rpx;
}

.link-text {
  color: #1989fa;
}

.action-btn {
  height: 90rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 30rpx;
  font-weight: 500;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 50rpx 0 30rpx;
}

.success-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 50rpx 0;
}

.success-icon {
  margin-bottom: 30rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.success-desc {
  font-size: 28rpx;
  color: #999;
}
</style>
